/* Copyright (c) 2016-2020 Enfry Ltd. All Rights Reserved.
 * 
 * This software is the confidential and proprietary information of Enfry. 
 * You shall not disclose such Confidential Information
 * and shall use it only in accordance with the terms of the agreements
 * you entered into with Enfry.
 */
package com.enfry.common.util.httpclient;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;

import com.enfry.common.util.Streams;

/**
 *  HTTP/HTTPS GET访问类，把HttpURLConnection的流转化成ByteArrayInputStream，该类为非文本响应内容时使用
 *	HttpDownload 大文件下载，请使用HttpDownload替换，以防止内存使用过大
 * @Title com.enfry.util.httpclient.HttpGetStream
 * @author Penghu
 * @date 2016年11月16日
 */
public class HttpGetStream extends HttpClient
{
    private ByteArrayOutputStream out;
    
    public HttpGetStream(String url)
    {
        super(url, _GET_);
    }
    
    /** 重写获取HTTP结果 */
    public HttpResult getResult()
    {
        return new HttpResult(responseStatus, responseText, out==null?null:out.toByteArray());
    }
    
    /** 获取输入流 */
    public InputStream getInputStream()
    {
        return new ByteArrayInputStream(out.toByteArray());
    }
    
    /** 获取字节数组 */
    public byte[] getBytes()
    {
        return out.toByteArray();
    }
    
    protected void doReadResponseContent(HttpURLConnection conn) throws IOException
    {
        if (responseStatus == _302_FOUND_)
        {//重定向
            responseText = conn.getHeaderField("Location");
            return;
        }
        
        if (responseStatus != _200_OK_)
        {//错误
            responseText = "调用服务端接口失败，错误码："+responseStatus;
            return;
        }
        
        //成功
        out = new ByteArrayOutputStream();
        Streams.putBytes(conn.getInputStream(), out);
        
        responseText = "调用成功";
    }
}
